package cn.edu.zafu.bigdata.bd121.file;

import java.io.*;

/**
 * 完成课本RhymingWords代码，验证文件管道操作，words文件存储在files目录下的words.txt。
 *
 * @author 202211090121
 */
public class RhymingWords {

    /**
     * 创建管道，启动单词逆序线程
     *
     * @param source 输入流
     * @return 输出流
     */
    public static Reader reverse(Reader source) throws IOException {
        BufferedReader in = new BufferedReader(source);
        PipedWriter pipedOut = new PipedWriter();
        PipedReader pipedIn = new PipedReader(pipedOut);
        PrintWriter out = new PrintWriter(pipedOut);
        new ReverseThread(out, in).start();
        return pipedIn;
    }

    /**
     * 排序线程
     *
     * @param source 输入流
     * @return 输出流
     */
    public static Reader sort(Reader source) throws IOException {
        BufferedReader in = new BufferedReader(source);
        PipedWriter pipedOut = new PipedWriter();
        PipedReader pipedIn = new PipedReader(pipedOut);
        PrintWriter out = new PrintWriter(pipedOut);
        new SortThread(out, in).start();
        return pipedIn;
    }

    public static void main(String[] args) throws IOException {
        FileReader words = new FileReader("src/main/java/cn/edu/zafu/bigdata/bd121/file/word.txt");
        Reader rhymedWords = reverse(sort(words));
        BufferedReader in = new BufferedReader(rhymedWords);
        String word;
        while ((word = in.readLine()) != null) {
            System.out.println(word);
        }
        words.close();
        rhymedWords.close();
    }
}
